<template>
  <div class="scrollable-form">
    
    <el-form
      ref="ruleForm"
      :rules="rules"
      :model="formData"
      label-width="200px"
      class="custom-form"
      v-loading="loading"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="中文名" prop="chineseName">
            <el-input v-model="formData.chineseName" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="学名" prop="scientificName">
            <el-input v-model="formData.scientificName" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="科名（中文名）">
            <el-input v-model="formData.familyChinese" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="科名（学名）">
            <el-input v-model="formData.familyLatin" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="属名（中文名）">
            <el-input v-model="formData.genusChinese" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="属名（学名）">
            <el-input v-model="formData.genusLatin" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="栖息地描述">
            <el-input v-model="formData.habitatDesc" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="保护等级">
            <el-input v-model="formData.protectionLevel" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="利用价值">
            <el-input v-model="formData.utilValue" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="物种描述">
            <el-input v-model="formData.speciesFeatureDesc" type="textarea" rows="6"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <!-- 在这里添加上传图片 -->
          <el-form-item label="物种照片">
            <el-upload
              ref="upload"
              class="upload-demo"
              :action="actionUrl"
              :data="{ ydbh: formData.id }"
              :on-success="handleUploadSuccess"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :before-upload="beforeFileUpload"
              list-type="picture-card"
              
            >
              <i class="el-icon-plus" />
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
        <el-row>
        <el-col :span="24">
          <!-- 在这里添加上传图片 -->
          <el-form-item label="生境照片">
            <el-upload
              ref="uploadHabitat"
              class="upload-demo"
              :action="actionUrl"
              :data="{ ydbh: formData.id }"
              :on-success="handleUploadSuccess1"
              :on-preview="handlePictureCardPreview1"
              :on-remove="handleRemove1"
              :file-list="fileList1"
              :before-upload="beforeFileUpload"
              list-type="picture-card"
              
            >
              <i class="el-icon-plus" />
            </el-upload>
            <el-dialog :visible.sync="dialogVisible1">
              <img width="100%" :src="dialogImageUrl1" alt="" />
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item size="large">
            <el-button style="margin-right: 8px" @click="goBack"
              >返回</el-button
            >
            <el-button type="primary" @click="onSubmit('ruleForm')">{{
              pageTitle
            }}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import commonOper from "../../../../utils/commonOper";
import config, { webapiUrl } from "@/config/config.js";
import { getToken } from '@/utils/auth' ;
export default {
  components: {},
  data() {
    return {
      pageTitle: "", // 用于展示页面标题
      formData: {
        id:'',
        chineseName: '',
        scientificName: '',
        familyChinese: '',
        familyLatin: '',
        genusChinese: '',
        genusLatin: '',
        photoId: '',
        sdm: '',
        speciesId: null,
        speciesFeatureDesc: null,
        habitatDesc: null,
        protectionLevel: null,
        utilValue: null,
        habitatPhotoId: null
      }, // 表单数据
      loading:true,
      rules: {
          chineseName: [
            { required: true, message: '请输入中文名', trigger: 'blur' }
          ],
          scientificName: [
            { required: true, message: '请输入学名', trigger: 'blur' }
          ],
      },
      actionUrl:config.webapiUrl+"rest//uploadpic",
      options: [], // 用于存储层级数据
      filteredData: [], // 所有属数据

      dialogImageUrl: "",
      dialogImageUrl1: "",
      dialogVisible: false,
      dialogVisible1: false,
      // imageNames: [], // 用于存储上传的图片名字
      fileList: [], // 添加这个数据用于存储上传的文件列表
      fileList1: [], // 添加这个数据用于存储上传的文件列表
    };
  },
  mounted() {
    // 获取传递的参数
    // const routeParams = this.$route.params;
    //this.getSmc();

    // 判断是否是新增页面
    if (!this.$route.query.data) {
      this.pageTitle = "新增";
      this.loading=false;
    } else {
      this.pageTitle = "修改";
      this.querySpeciesInfo(this.$route.query.data);
    }
  },

  methods: {
    querySpeciesInfo(id){
      let that = this;
        let params = {
          this: that,
          url: config.webapiUrl+"nd/dw/getWzBySpeciesId?speciesId="+id,
          data: {
            params: {
              pageNum: that.currentPage,
              pageSize: that.pageSize,
            },
            headers: {
              Authorization: "Bearer " +getToken(),
            },
          },
          successFunc: function (response) {
            that.loading = false;
            let data = response.data.data;
            console.log(data);
            that.formData=data;

            let baseURL = "http://49.232.236.127/wzimg/";
            let pathsArray = [];
            let pathsArray1 = [];

            if(data.photoId!=null&&data.photoId.length>0){
              var photoArr = data.photoId.split(",");// 使用 trim() 移除可能存在的空格
              photoArr.forEach(function(photo) {
              pathsArray.push({name:photo,url:baseURL+photo});
            });
            }
          this.fileList=pathsArray;

          if(data.habitatPhotoId!=null&&data.habitatPhotoId.length>0){
              var photoArr = data.habitatPhotoId.split(",");// 使用 trim() 移除可能存在的空格
              photoArr.forEach(function(photo) {
              pathsArray1.push({name:photo,url:baseURL+photo});
            });
            }
            this.fileList1=pathsArray1;

          },
          failFunc: function (response) {
            that.loading = false;
            let params = {
              this: that,
              title: "提示",
              message: "网络异常，请稍后重试！" + response,
              successFunc: function () {},
            };
            commonOper.showWarnAlert(params);
          },
        };
        commonOper.HttpGet(params);
    },
    beforeFileUpload(file){
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 50;

        if (!isJpgOrPng) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 50MB!');
        }
        return isJpgOrPng && isLt2M;
    },
    handleRemove(file, fileList) {
      // 处理文件删除逻辑
      this.fileList=fileList;
    },
    handleRemove1(file, fileList) {
      // 处理文件删除逻辑
      this.fileList1=fileList;
    },

    handleUploadSuccess(response, file, fileList) {
      
      if (response.code == -1) {
        this.$message.error(response.msg);
        // 删除重复的文件
        // console.log("delete before:",this.fileList);
        // const index = this.fileList.findIndex(
        //   (item) => item.name === file.name
        // );
        // console.log("index:",index);
        // if (index !== -1) {
        //   this.fileList.splice(index, 1);
        // }
        // console.log("delete after:",this.fileList);
        return;
      }
      this.fileList=fileList;
      this.$message.success("物种图片上传成功");
     
    },

    handleUploadSuccess1(response, file, fileList) {
      
      if (response.code == -1) {
        this.$message.error(response.msg);
        // 删除重复的文件
        // console.log("delete before:",this.fileList);
        // const index = this.fileList.findIndex(
        //   (item) => item.name === file.name
        // );
        // console.log("index:",index);
        // if (index !== -1) {
        //   this.fileList.splice(index, 1);
        // }
        // console.log("delete after:",this.fileList);
        return;
      }
      this.fileList1=fileList;
      this.$message.success("物种图片上传成功");
     
    },
    // 预览图片
    handlePictureCardPreview(file) {
     
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePictureCardPreview1(file) {
     
      this.dialogImageUrl1 = file.url;
      this.dialogVisible1 = true;
    },
    onSubmit(formName) {
      // 调用触发上传的方法
      //this.triggerUpload();
      //console.log("submit!", this.formData);
      let that = this;
      let surl='';
      let isSubmit=false;
      this.$refs[formName].validate((valid) => {
          if (valid) {
            isSubmit=true;
          }
      });
      //处理照片
      
      let pthtostr="";
      this.fileList.forEach(function(item) {
        if(item.response!=undefined){
           pthtostr+=item.response.data.newFileName+",";
        }else{
           pthtostr+=item.name+",";
        } 
      });
      this.formData.photoId=pthtostr.slice(0, -1);

      let pthtostr1="";
      this.fileList1.forEach(function(item) {
        if(item.response!=undefined){
           pthtostr1+=item.response.data.newFileName+",";
        }else{
           pthtostr1+=item.name+",";
        } 
      });
      this.formData.habitatPhotoId=pthtostr1.slice(0, -1);

      if(!isSubmit){
        this.$message.error('数据校验错误，中文名和拉丁名不能为空！');
        return;
      }
      if (this.pageTitle === "新增") {
        surl=config.webapiUrl+"nd/dw/addSpecies";
      } else if (this.pageTitle === "修改") {
        surl=config.webapiUrl+"nd/dw/editSpecies";

      }

      that.loading = true;
      let paramscommo = {
        this: that,
        url: surl,
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        data: that.formData,
        successFunc: function (response) {
          that.loading = false;
          if (response.data.code == 0) {
            that.$message.success("保存成功！");
             // 延迟一下再返回，让用户看到成功提示
            setTimeout(() => {
              this.goBack();
            }, 1000);
          } else {
            let params = {
              this: that,
              title: "提示",
              message: "保存失败，请稍后重试！" + response.data.msg,
              successFunc: function () {},
            };
            commonOper.showWarnAlert(params);
          }
        },
        failFunc: function (response) {
          that.loading = false;
          let params = {
            this: that,
            title: "提示",
            message: "网络异常，请稍后重试！" + response.data.data,
            successFunc: function () {},
          };
          commonOper.showWarnAlert(params);
        },
      };
      commonOper.HttpPost(paramscommo);
    },
    goBack() {
      // 在这里执行返回操作的逻辑
      this.$router.go(-1);
    },
    
    // 根据 sdm 找到对应的数据
    findDataBySdm(sdm) {
      const selectedData = this.filteredData.find((item) => item.dmz === sdm);
      console.log("666", selectedData);
      return selectedData || null;
    },
    // 拿到属名称
    getSmc() {
      this.$api
        .getSmcData()
        .then((res) => {
          console.log("res", res);
          // 处理科的数据
          const scientificOptions = [];
          this.filteredData = res.data.data;
          // console.log("数据", this.filteredData);
          // 找到所有的科
          const scientificData = this.filteredData.filter(
            (item) => item.jb === "5"
          );
          // console.log("222", scientificData);
          // 遍历科，为每个科添加属
          scientificData.forEach((scientific) => {
            const speciesInScientific = this.filteredData.filter(
              (item) => item.jb === "6" && item.dmz.includes(scientific.dmz)
            );

            const speciesOptions = speciesInScientific.map((species) => ({
              value: species.dmz,
              label: species.dmmc1,
            }));
            // console.log("aa", speciesOptions);
            scientificOptions.push({
              value: scientific.dmz,
              label: scientific.dmmc1,
              children: speciesOptions,
            });
          });
          // console.log("bbbb", scientificOptions);
          // 设置给 options
          this.options = scientificOptions;
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
};
</script>

<style>
/* 你的样式 */

/* 设置表单的边框和背景色 */
.custom-form {
  border: 1px solid #ebeef5;
  /* background-color: #f5f7fa; */
  padding: 20px; /* 可根据需要调整 */
  border-radius: 5px; /* 可根据需要调整 */
  text-align: center;
}

/* 设置表单项的样式，例如边距和字体大小 */
.el-form-item {
  margin-bottom: 15px;
  padding: 10px;
}

/* 自定义带有 label 的表单项样式 */
.el-form-item label {
  background-color: #f5f7fa;
  color: #000;
  /* padding: 10px; */
  /* border-radius: 4px; */
  display: inline-block;
  text-align: center;
}

/* 设置输入框的样式，例如边框颜色和字体大小 */
.el-input {
  /* border: 1px solid #dcdfe6; */
  border-radius: 4px;
  font-size: 14px;
  /* padding: 10px; */
}

/* 设置按钮的样式 */
.el-button {
  margin-right: 8px;
}


.btn {
  width: 100%;

  padding: 10px 16px;
  background: rgb(255, 255, 255);
  text-align: center;
}

.scrollable-form {
  max-height: 90vh;/*  设置最大高度为80%视口高度，可根据需要调整 */
  overflow-y: auto; /* 启用垂直滚动 */
}
.el-select {
  display: block;
}
.el-cascader {
  display: block;
}

/* 自定义成功消息样式 */
.custom-message-success {
  background: linear-gradient(135deg, #4caf50 0%, #45a049 100%) !important;
  border: none !important;
  border-radius: 8px !important;
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3) !important;
}

.custom-message-success .el-message__content {
  color: white !important;
  font-weight: bold !important;
}

.custom-message-success .el-message__icon {
  color: white !important;
}

/* 表单提交按钮美化 */
.el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
  border-radius: 6px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

/* 表单容器美化 */
.el-form {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
}
</style>
